import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import { message } from 'antd';

// 与后端约定的响应数据格式
interface ResponseStructure {
  success: boolean;
  data: any;
  status?: number;
  errorMessage?: string;
  // showType?: ErrorShowType;
}

/**
 * @name 错误处理
 * pro 自带的错误处理， 可以在这里做自己的改动
 * @doc https://umijs.org/docs/max/request#配置
 */
export const errorConfig: RequestConfig = {
  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      // 拦截请求配置，进行个性化处理。
      if (localStorage.getItem('token') !== null) {
        const authorization = 'Bearer ' + localStorage.getItem('token')?.replaceAll('"', '') + ' ' + localStorage.getItem('tokenIssueTime');
        config.headers = { ...config.headers, authorization };
        return { ...config };
      } else {
        const authorization = 'Bearer ';
        return { ...config, authorization };
      }
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    (response) => {
    if(response?.config?.responseType === 'blob'){
      return response;
    }

      // 拦截响应数据，进行个性化处理
      const { data } = response as unknown as ResponseStructure;
      const { headers } = response;
      if (headers.authorization) {
        //重新设置新的token
        const parts = headers.authorization.trim().split(' ');
        const [, token, tokenIssueTime] = parts;
        localStorage.setItem('token', token);
        localStorage.setItem('tokenIssueTime', tokenIssueTime);
      }
      if (data?.status !== 200 && data.message) {
        message.error(data.message);
      }
      return response;
    },
  ],
};
